package classloader;

import xianchenglock.E;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author Jim
 * @date 12:23 上午 2022/4/3
 * @description 自定义类加载器
 * @email:huwmz04153277@126.com
 */
public class  MyClassloader extends ClassLoader {
    public MyClassloader(ClassLoader parent) {
        super(parent);
    }

    public MyClassloader() {
        super();
    }

    @Override
    public Class findClass(String name) {

        byte[] b = loadClassData(name);
        name = name + ".class";
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name)  {
        FileInputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("target/classes/"+name.replace(".","/")+".class");
            outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[2];
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            return outputStream.toByteArray();

        }catch (Exception e){
e.printStackTrace();
        }finally {
            if (outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }}
            if (inputStream != null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }}
        }
        return null;
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        MyClassloader m = new MyClassloader();
        Class c = m.loadClass("classloader.MyClass");

        System.err.println(c.getClassLoader());

        MyClass myClass =(MyClass) c.newInstance();
        myClass.say();
    }



}
class MyClass{
public void say(){
    System.out.printf("1111");
}
}